package com.htjc.integral.conversion.tokenUtil.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.commons.service.util.StringUtil;
import com.htjc.integral.conversion.enums.Constant;
import com.htjc.integral.conversion.mapper.EcPartnerExtServiceCommonMapper;
import com.htjc.integral.conversion.mapper.EcPartnerInvitecodeServiceCommonMapper;
import com.htjc.integral.conversion.tokenUtil.CommonTools;
import com.htjc.integral.conversion.tokenUtil.VerifyCodeConfig;
import com.htjc.integral.conversion.tokenUtil.VerifyCodeUtil;
import com.htjc.integral.conversion.tokenUtil.service.IUSCClientService;
import com.htjc.integral.conversion.tokenUtil.service.IUserService;
import com.htjc.integral.conversion.util.SgccMallUtil;
import com.htjc.integral.model.conversion.EcPartner;
import com.htjc.integral.model.conversion.EcPartnerInvitecode;
import com.sgcc.asc.base.http.rest.RestUtils;


@Service
public class UserServiceImpl implements IUserService{
	
	
	private final static Log log = LogFactory.getLog(UserServiceImpl.class);

	@Autowired
	private EcPartnerExtServiceCommonMapper partnerExtMapper;
	
	@Autowired
	private EcPartnerInvitecodeServiceCommonMapper ecPartnerInvitecodeMapper;
	
	@Autowired
	private IUSCClientService uSCClientService;
	
	/**
	 * 通过token获取userid
	 * @param uscInfo  为空
	 * @param token
	 * @return
	 */
	public String makeTokenUserId(String uscInfo,String token){
		//根据token获取用户信息 （通过sip去外部请求）
		String uscInfos = uSCClientService.CheckTokenBackUserId(token);
		if(StringUtils.equals("0000", JSON.parseObject(uscInfos).getJSONObject("srvrt").getString("resultCode"))){
			String userId = "";
			String userName = "";
			userId = JSON.parseObject(uscInfos).getJSONObject("bizrt").getJSONObject("userInfo").getString("partnerId");
			userName = JSON.parseObject(uscInfos).getJSONObject("bizrt").getJSONObject("userInfo").getString("loginAccount");		
			this.DataSyncToEcPartner(userId, userName);
		}
		log.info("K测试开始------------------------------");
		log.info("传的参数值uscInfo为:"+uscInfo);
		log.info("传的参数值token为:"+token);
		log.info("调用底层方法通过token获取userId信息:"+uscInfos);
		log.info("K测试结束------------------------------");
		return uscInfos;
	}
	
/*	public String logOut(String uscInfo,String quInfo){
		String info = uSCClientService.logout(uscInfo,quInfo);
		return info;
	}*/
	
	//111
	public String checkUserIsOk(String partnerId) {
		return	partnerExtMapper.checkUserIsOk(partnerId);
	}
	
	//111
	public EcPartner getPartnerByUserId(String userid){
		return this.getPartnerByIdMongodb(userid);
	}
	
	//111
	private EcPartner getPartnerByIdMongodb(String partnerId){
		EcPartner ecPartner = null;
		try {	
		    JSONObject uscInfo = new JSONObject();
			uscInfo.put("tenant", Constant.TENANT_CODE_PARAM_VALUE);
			uscInfo.put("member", Constant.APP_CODE_PERSONAL);
			 String ticketAuthUrl = SgccMallUtil.getInstance().getConfValue("site.usc.server.url");
				Map<String,String> params=new HashMap<String,String>();
				params.put("uscInfo",uscInfo.toString());
				params.put("userId",partnerId);
				String	resultJson = null;
				try {
					resultJson = RestUtils.post(ticketAuthUrl+"/malllogin/getuserinfoNoToken",params);
				} catch (IOException e) {
					log.info("usc-server调用日志:"+e);
				}
	           if(StringUtils.equals(Constant.RE_CODE_0000,
	        	JSON.parseObject(resultJson).getJSONObject("srvrt").getString("resultCode"))){
	        	   CommonTools commonTools = new CommonTools();
	          	 Object object =JSON.parseObject(resultJson).getJSONObject("bizrt").getJSONObject("userInfo");
	       		if(object!=null){
	       			 ecPartner = commonTools.userInfoJsonToPartner(JSON.toJSONString(object));
	       		  }	 
	           }
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据id查询用户信息异常", e);
		}
	   
           return ecPartner;
	}
	
	//111
	public String checkemailIsOk(String email) {
		return partnerExtMapper.checkEmailIsOk(email);
	}
	
	//111
	public String checkMobileIsOk(String mobile) {
		return partnerExtMapper.checkMobileIsOk(mobile);
	}
	
	//111
	public void DataSyncToEcPartner(String userId,String userName) {
		try {
			log.info("********************同步用户信息开始*************************");
			log.info("用户id:"+userId);
			if(StringUtils.isBlank(userId)){
				return;
			}
			String  result = this.checkUserIsOk(userId);
			log.info("从商城用户表中获取用户id:"+result);
			EcPartner partnerUsc= this.getPartnerByUserId(userId);
			String mobile = partnerUsc.getMobile();
			log.info("session-mobile--->"+mobile);
			String mobiles = "";
			if(StringUtil.isNotNull(mobile)){
				mobiles = this.checkMobileIsOk(mobile);
				log.info("Ec_PARTNER中mobiles==>"+mobiles);
			}
			String email = partnerUsc.getEmail();
			log.info("email-mobile--->"+email);
			String emails = "";
			if(StringUtil.isNotNull(email)){
				emails = this.checkemailIsOk(email);
				log.info("Ec_PARTNER中emails==>"+emails);
			}
			log.info("1->"+StringUtils.isBlank(result)+"2->"+StringUtils.isBlank(mobiles)+"3->"+StringUtils.isBlank(emails));
			if(StringUtils.isBlank(result) && StringUtils.isBlank(mobiles) && StringUtils.isBlank(emails)){
				log.info("用户:"+userName+"的partnerId:"+partnerUsc.getPartnerId());
				//个人商城userId=8位，统一用户userId=32位
				if(userId.length()==32){
					partnerUsc.setApplyWay("40");//统一平台引流用户:40
					log.info("用户:"+userName+"为统一平台引流用户");
				}
				if(StringUtils.isBlank(partnerUsc.getUserType())){
					partnerUsc.setUserType("1");
				}
				this.registerToEcPartner(partnerUsc);
				log.info("用户:"+userName+"已同步到EcPartner表");
			}else{
				log.info("用户:"+userName+"无需同步到EcPartner表");
			}
		} catch (Exception e) {
			log.error("同步用户数据异常", e);
		}
		log.info("********************同步用户信息结束*************************");
	}
	
	//111
	public int registerToEcPartner(EcPartner  partner) {
        int count = partnerExtMapper.insert(partner);
         if(count>0){ 
         	//为新注册用户生成邀请码	
         	System.out.println("为新注册用户生成邀请码");
         	this.insertEcPartnerInvitecode(partner.getPartnerId());
         }
		return count;	
	}
	
	//111
	public int  insertEcPartnerInvitecode(String partnerId){ 
		 EcPartnerInvitecode ecPartnerInvitecode = new EcPartnerInvitecode();
		 ecPartnerInvitecode.setPartnerId(partnerId);
 	     ecPartnerInvitecode.setInviteCode(VerifyCodeUtil.getCharAndNumr(VerifyCodeConfig.USER_INVITE_CODE_LENGTH));
 	     ecPartnerInvitecode.setInviteTime(new Date());
 	     return	ecPartnerInvitecodeMapper.insert(ecPartnerInvitecode);
	}
	
}
